package bigoo.peer.message;

import bigoo.common.communication.AbstractMessage;
import bigoo.common.communication.InvalidMessageException;
import bigoo.common.communication.Message;
import bigoo.common.communication.MessageBuilder;

public class ImAliveMessage extends AbstractMessage {

    public static final String MSG_IDENTIFIER = "IM_ALIVE";

    private int port;
    private String address;

    public ImAliveMessage(String senderID, String address, String port) {
	super(senderID, MSG_IDENTIFIER);
	this.address = address;
	this.port = Integer.parseInt(port);
    }

    @Override
    public String getRawMessage() {
	return this.getSenderID() + SEPARATOR + MSG_IDENTIFIER + SEPARATOR + address + PARAM_SEPARATOR + port + END_OF_MESSAGE;
    }

    public int getPort() {
	return port;
    }

    public String getAddress() {
	return address;
    }

    public static class Builder implements MessageBuilder {
	@Override
	public Message parseMessage(String rawMessage) throws InvalidMessageException {
	    try {
		String senderID = parseSenderID(rawMessage);
		String[] params = parseListParams(rawMessage);
		String[] param = parseParams(params[0]);
		return new ImAliveMessage(senderID, param[0], param[1]);
	    } catch (ArrayIndexOutOfBoundsException e) {
		throw new InvalidMessageException("Missing fields!");
	    }
	}
    }

}
